package com.qubuyer.business.home.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import com.qubyer.widget.adapter.IHeader

abstract class HomeItemView<D, DB : ViewDataBinding>(lifecycleOwner: LifecycleOwner, val mContext: Context, parent: ViewGroup, val layoutId: Int) : IHeader {

    private var itemView: View
    var dataBinding: DB = DataBindingUtil.inflate(LayoutInflater.from(mContext), layoutId, parent, false)
    var bindingData: D? = null

    init {
        dataBinding.lifecycleOwner = lifecycleOwner
        itemView = dataBinding.root
    }

    fun onDataSet(data: D?) {
        if (data == null) {
            itemView.isVisible = false
            return
        }
        if (data is List<*> && data.isEmpty()) {
            itemView.isVisible = false
            return
        }
        if (bindingData != null && bindingData == data) {
            return
        }
        if (bindingData != null && isTheSameData(bindingData!!, data)) {
            return
        }
        itemView.isVisible = true
        bindingData = data
        bindView(data)
    }

    override fun getViewDataBinding(): ViewDataBinding {
        return dataBinding
    }

    open fun isTheSameData(origin: D, now: D): Boolean {
        return false
    }

    abstract fun bindView(data: D)
}